package com.lk.netty;

import com.lk.netty.handler.ServerHandler;
import com.lk.netty.handler.ServerInitializer;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.PooledByteBufAllocator;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

import java.util.concurrent.ThreadFactory;

public class EchoServer {

    private final int port;

    public EchoServer(int port) {
        this.port = port;
    }

    public void run() throws Exception {

        // 创建自定义的线程工厂，设置线程优先级为最高
        ThreadFactory bossThreadFactory = new ThreadFactory() {
            @Override
            public Thread newThread(Runnable r) {
                Thread t = new Thread(r);
                t.setPriority(Thread.MAX_PRIORITY);
                return t;
            }
        };

        // 创建自定义的线程工厂，设置线程优先级为最高
        ThreadFactory workerThreadFactory = new ThreadFactory() {
            @Override
            public Thread newThread(Runnable r) {
                Thread t = new Thread(r);
                t.setPriority(Thread.MAX_PRIORITY - 2);
                return t;
            }
        };

        EventLoopGroup bossGroup = new NioEventLoopGroup(bossThreadFactory);
        EventLoopGroup workerGroup = new NioEventLoopGroup(workerThreadFactory);

        try {
            ServerBootstrap b = new ServerBootstrap();
            b.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
                    .childHandler(new ServerInitializer())
		            .childOption(ChannelOption.AUTO_READ, false)
                    .childOption(ChannelOption.SO_BACKLOG, 65535)
                    .childOption(ChannelOption.TCP_NODELAY, true)
                    .option(ChannelOption.TCP_NODELAY, true);
            // 启动服务器
            b.bind(port).sync().channel().closeFuture().sync();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }

    public static void main(String[] args) throws Exception {
        int port = 8080;
        new EchoServer(port).run();
    }


}